package com.qf.web.job;

import com.qf.common.base.exception.DaoException;
import com.qf.common.base.result.ResultCode;
import com.qf.web.entity.Coupon;
import com.qf.web.mapper.CouponMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
@Configurable
@EnableScheduling
@Slf4j
public class ScheduledTasks{

    @Resource
    CouponMapper couponMapper;


    public static final Integer NUMBER_ZERO=0;

    public static final Integer  STATUS_BEFORE=0;
    public static final Integer  STATUS_BEING=1;
    public static final Integer  STATUS_END=2;
    public static final String TASY_NAME="绿子哥";

    //每3秒执行一次
    @Scheduled(cron = "*/3 * * * * ?")
    public void reportCurrentByCron(){
       /* log.info(TASY_NAME);*/
        List<Coupon> couponslist = couponMapper.selectList(null);
        Date date = new Date();

        for (Coupon coupon:couponslist) {
          //判断当前时间是否在发放时间之前
            if (date.before(coupon.getReleaseStartDate())){
                //判断状态值是否正确
                if (coupon.getStatus()==STATUS_BEFORE){
                    //跳过本次循环
                    continue;
                }
                //设置代金券状态值
                Integer integer = couponMapper.updateStatus(coupon.getCouponId(), STATUS_BEFORE);
                if (integer==NUMBER_ZERO){
                    throw new DaoException(ResultCode.DATA_IS_WRONG);
                }
            }else if (date.after(coupon.getReleaseStartDate()) && date.before(coupon.getReleaseEndDate())){
                if (coupon.getStatus()==STATUS_BEING){
                    continue;
                }
                Integer integer = couponMapper.updateStatus(coupon.getCouponId(), STATUS_BEING);
                if (integer==NUMBER_ZERO){
                    throw new DaoException(ResultCode.DATA_IS_WRONG);
                }
            }else {
                if (coupon.getStatus()==STATUS_END){
                    continue;
                }
                Integer integer = couponMapper.updateStatus(coupon.getCouponId(), STATUS_END);
                if (integer==NUMBER_ZERO){
                    throw new DaoException(ResultCode.DATA_IS_WRONG);

                }
            }

        }
    }



}